import router from './router'
import store from './store'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './utils/auth'
import { Message } from 'element-ui'
// 白名单
const whileList = ['/login', '/register', '/home', '/searchteacher', '/personal/userconsume', '/socket', '/class/allclass', '/class/classInfo']
router.beforeEach(async(to, from, next) => {
  Nprogress.start()
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next('/')
      Nprogress.done()
    } else {
      if (store.getters.username) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo')
          next()
        } catch (err) {
          await store.dispatch('user/resetToken')
          Message.error(err || 'news Error')
          next(`/login?redirect=${to.path}`)
          Nprogress.done()
        }
      }
    }
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      Nprogress.done()
    }
  }
})
router.afterEach((to, from, next) => {
  Nprogress.done()
})

